﻿#if WINDOWS_UWP || NETFX_CORE
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Windows.Storage;

using Outcoder.Data.Serialization;

namespace Outcoder.ComponentModel.StatePreservation
{
	public class TransientState : ITransientState
	{
		internal static readonly string dictionaryKey = "Calcium_TransientState";

		IDictionary<string, object> stateDictionary = new Dictionary<string, object>();

		bool loaded;

		public IDictionary<string, object> StateDictionary
		{
			get
			{
				if (!loaded)
				{
					Load();
				}

				return stateDictionary;
			}
		}

		public Task LoadAsync()
		{
			Load();

			return Task.FromResult(0);
		}

		public void Load()
		{
			var bytes = ApplicationData.Current.LocalSettings.Values[dictionaryKey] as byte[];
			if (bytes == null)
			{
				return;
			}

			stateDictionary = SilverlightSerializer.Deserialize<IDictionary<string, object>>(bytes);

			loaded = true;
		}

		public Task SaveAsync()
		{
			Save();

			return Task.FromResult(0);
		}

		public void Save()
		{
			if (stateDictionary == null || !stateDictionary.Any())
			{
				ApplicationData.Current.LocalSettings.Values[dictionaryKey] = null;
				return;
			}

			var bytes = SilverlightSerializer.Serialize(stateDictionary);

			ApplicationData.Current.LocalSettings.Values[dictionaryKey] = bytes;
		}

		public void Clear()
		{
			stateDictionary.Clear();
			Save();
		}
	}
}
#endif